package com.hnichr.ump.talent.library.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hnichr.ump.common.talent.library.entity.Skills;
import com.hnichr.ump.common.talent.library.service.SkillsService;
import com.hnichr.ump.talent.library.provider.SyncPolicyProvider;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class SkillsSyncPolicyProvider implements SyncPolicyProvider {
    private static final String KEY = "skillsList";

    @Autowired
    private SkillsService skillsService;

    @Override
    public boolean support(JSONObject jsonObject) {
        return jsonObject.containsKey(KEY);
    }

    @Override
    @Transactional
    public void sync(String syncDate, JSONObject jsonObject) {
        JSONArray skillsList = jsonObject.getJSONArray(KEY);
        if(CollectionUtils.isEmpty(skillsList)){
            return;
        }
        for(Object skillsObject:skillsList){
            if(skillsObject instanceof JSONObject){
                JSONObject skillsJSONObject = (JSONObject) skillsObject;
                Skills skills = new Skills();
                skills.setId(skillsJSONObject.getString("id"));
                skills.setDelFlag(skillsJSONObject.getBoolean("delFlag"));
                skills.setUserId(skillsJSONObject.getString("userId"));
                if(skillsJSONObject.containsKey("createTime")){
                    skills.setOrginalCreateTime(new Date(skillsJSONObject.getLong("createTime")));
                }
                if(skillsJSONObject.containsKey("updateTime")){
                    skills.setOrginalUpdateTime(new Date(skillsJSONObject.getLong("updateTime")));
                }

                skills.setName(skillsJSONObject.getString("name"));
                skills.setTime(skillsJSONObject.getInteger("time"));
                skills.setLevel(skillsJSONObject.getString("level"));
                skills.setResumeId(skillsJSONObject.getString("resumeId"));
                skills.setSyncDate(syncDate);
                skillsService.merge(skills);
            }
        }
    }
}
